package com.nettywork.hearbeat;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;

import java.util.concurrent.*;

public class NettyHearbeatClient {

    private Bootstrap bootstrap;
    private int port;
    private String host;
    private EventLoopGroup workGroup;

    public static void main(String args[]) {
        NettyHearbeatClient client = new NettyHearbeatClient(6999, "127.0.0.1");
        client.connect();
    }

    public NettyHearbeatClient(int port, String host) {
        this.port = port;
        this.host = host;
        init();
    }

    public void init() {
        workGroup = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(workGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline channelPipeline = socketChannel.pipeline();
                        channelPipeline.addLast(new HearBeatClientHandler());
                    }
                });
    }

    public void connect(){
        ChannelFuture channelFuture = bootstrap.connect(host, port);
        Channel channel = channelFuture.channel();

        //断线重连监听
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if (channelFuture.isSuccess()) {
                    System.out.println("服务器连接成功!");
                    //如果连接成功 则发起心跳服务
                    if (channel.isActive()) {
                       // Executors.newScheduledThreadPool(1).scheduleAtFixedRate(new Runnable() {
                        channel.eventLoop().scheduleAtFixedRate(new Runnable() {
                            @Override
                            public void run() {
                                System.out.println("发送心跳到服务端");
                                String hearbeatPackage = channel.remoteAddress() + "心跳包";
                                ByteBuf byteBuf = Unpooled.copiedBuffer(hearbeatPackage.getBytes(CharsetUtil.UTF_8));
                                channel.writeAndFlush(byteBuf);
                            }
                        }, 0, 3, TimeUnit.SECONDS);
                    }
                } else {
                    System.out.println("正在重连服务器");
                    connect();
                }
            }
        });
//        try {
//            channelFuture.channel().closeFuture();
//        } finally {
//            workGroup.shutdownGracefully();
//        }
    }

    class HearBeatClientHandler extends ChannelInboundHandlerAdapter {

        NettyHearbeatClient client = new NettyHearbeatClient(6999, "127.0.0.1");

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ByteBuf byteBuf = (ByteBuf) msg;
            byte[] b = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(b);
            String result = new String(b);
            System.out.println(result);
            if ("idle close".equals(result)) {
                ctx.channel().close();
            }
        }

        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            ctx.channel().eventLoop().shutdownGracefully();
            client.connect();
        }
    }
}
